package com.atguigu.gulimall.order.web;


import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.OrderConfirmVo;
import com.atguigu.gulimall.order.vo.OrderSubmitVo;
import com.atguigu.gulimall.order.vo.SubmitOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

/**
 * @ClassName OrderWebController
 * @Description TODO
 * @Detail detail
 * @Author MyPC
 * @Date 2020/7/18
 * @Version 1.0
 */
@Controller
public class OrderWebController {

    @Autowired
    OrderService orderService;


    /**
     * 订单确认
     * @param model
     * @return
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo=orderService.confirmOrder();
        model.addAttribute("orderConfirmData",confirmVo);
        return "confirm";
    }

    /**
     * 下单功能
     * @param submitVo
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo submitVo, Model model, RedirectAttributes redirectAttributes){
        //1、创建订单、验令牌、验价格、锁库存
        SubmitOrderResponseVo responseVo=orderService.submitOrder(submitVo);
        //responseVo.getCode() == 0 代表一切正常
        if(responseVo.getCode() == 0){
            model.addAttribute("submitOrderResp",responseVo);
            //2、下单成功跳转到支付选择页
            return "pay";
        }else {
            String msg="下单失败：";
            switch (responseVo.getCode()){
                case 1 :msg+="订单信息过期，请再次提交"; break;
                case 2 : msg+="商品价格发送变化，请确认后再次提交";break;
                case 3 : msg+="商品库存不足";break;
            }
            redirectAttributes.addFlashAttribute("msg",msg);
            //3、下单失败重新回到订单确认页
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }
}
